﻿

/*设计一个自己的字符串类MyString，内部有一个私有成员char* sptr
该成员用于创建字符串对象时，
 在内部使用动态内存分配的方法分配一个字符数组用于存储字符串的内容。
为该类设计构造函数、析构函数（对象析构时，要释放分配的数组）
为该类设计返回字符串实际长度的成员函数
为该类设计输出字符串内容的成员函数
为该类设计实现字符串连接和字符串复制的成员函数。字符串连接和字符串复制时，
要求重新分配数组，并释放原有的数组。

main函数已经写好，请根据main函数的内容完成该类的设计：*/
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
using namespace std;
class MyString
{
	int len;
	char* sptr;
public:
	MyString()
	{
		sptr = new char[1];
		sptr[0] = '\0';
		len = 0;
		cout << "Object Constructed. No Memory Allocated." << endl;
	}
	MyString( const char*  s)
	{
		if (s)
		{
			len = (int)strlen(s);
			sptr = new char[len + 1];
			strcpy(sptr, s);
			cout << "Object Constructed. "<<len+1<<" Bytes Allocated." << endl;
		}
		
	}
	MyString(const MyString & mys)
	{
		len = mys.len;
		sptr = new char[len + 1];
		strcpy(sptr, mys.sptr);
		cout << "Object Constructed. " << len+1 << " Bytes Allocated." << endl;
	}

	void printString()
	{
		if (len == 0)
	{
			cout << "No Memory Allocated In This Object." << endl;
	}
		else
		{
			cout << sptr << endl;
		}
	}
	int getSize()
	{
		return len;
	}
	void stringCopy(MyString &mys)
	{
		cout << "String Copy, " << mys.len + 1 << " Bytes Reallocated And " <<len + 1 << " Bytes Freed." << endl;

		len = mys.len;
		sptr = new char[len + 1];
		strcpy(sptr, mys.sptr);
	}
	void stringCat(const MyString &mys)
	{
	cout << "String Connection, " << len + mys.len + 1 << " Bytes Reallocated And 6 Bytes Freed." << endl;
		len = len + mys.len;
		char* ss=strcat(sptr,mys.sptr);
		sptr = new char[len + 1];
		strcpy(sptr, ss);
	}
	~MyString()
	{
		if (sptr != NULL)
		{
			if (len != 0)
			{
			cout << "Object Destructed. " << len + 1 << " Bytes Freed." << endl;
				delete[] sptr;
			}
		
			if (len == 0)
		{
			cout << "Object Destructed. No Memory Freed." << endl;
		
		}
		}
	}
};
int main() {
	MyString s1;
	MyString s2("Hello");
	MyString s3(s2);

	s1.printString();
	s2.printString();
	s3.printString();

	cout << s1.getSize() << " " << s2.getSize() << " " << s3.getSize() << endl;

	MyString s4("HiChina");

	s2.stringCopy(s4);
	s2.printString();

	s3.stringCat(s4);
	s3.printString();

	return 0;
}